package com.wangnian.task.util;

import jodd.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by wangnian on 2017/3/16.
 */
@Component
public class EmailUtil {

    static final Logger logger = LoggerFactory.getLogger(EmailUtil.class);

    @Autowired
    MailSender mailSender;

    @Value(value = "${spring.mail.username}")
    private String username;

    @Value(value = "${spring.mail.sendTo}")
    private String sendTo;


    @Async
    public void sendEmail(String content) {
        logger.info("发送异常邮件");
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(username);
            message.setTo(sendTo);
            String ip = getLocalIP();
            if (!StringUtil.isBlank(ip)) {//如果没有获取到Ip,不用发邮件，这里不用env来判断，因为在windows环境下获取不到ip
                message.setSubject(getLocalIP() + "任务系统异常");
                message.setText(content);
                mailSender.send(message);
            }
        } catch (Exception e) {
            logger.warn("发送邮件消息失败=exception:{}", e);
        }
    }

    public String getLocalIP() {
        String ip = "";
        try {
            Enumeration<?> e1 = NetworkInterface.getNetworkInterfaces();
            while (e1.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) e1.nextElement();
                if (!ni.getName().equals("eth0")) {
                    continue;
                } else {
                    Enumeration<?> e2 = ni.getInetAddresses();
                    while (e2.hasMoreElements()) {
                        InetAddress ia = (InetAddress) e2.nextElement();
                        if (ia instanceof Inet6Address)
                            continue;
                        ip = ia.getHostAddress();
                    }
                    break;
                }
            }
        } catch (SocketException e) {
            logger.info("获取系统的Ip为空");
            return ip;
        }
        return ip;
    }

}
